<template>
  <div class="upload-container">
    <el-button :style="{background:color,borderColor:color}" icon="el-icon-upload" size="mini" type="primary" @click=" dialogVisible=true">
      upload
    </el-button>
    <el-dialog :visible.sync="dialogVisible">
      <el-upload
        :on-change="getFile"
        :http-request="uploadImage"
        :multiple="true"
        :file-list="fileList"
        :show-file-list="true"
        :on-remove="handleRemove"
        class="editor-slide-upload"
        action="https://httpbin.org/post"
        list-type="picture-card"
      >
        <el-button size="small" type="primary">
          点击上传
        </el-button>
      </el-upload>
      <el-button @click="dialogVisible = false">
        取消
      </el-button>
      <el-button type="primary" @click="handleSubmit">
        确认
      </el-button>
    </el-dialog>
  </div>
</template>

<script>
  // import { getToken } from 'api/qiniu'

  export default {
    name: 'EditorSlideUpload',
    props: {
      color: {
        type: String,
        default: '#1890ff',
        // action:"https://httpbin.org/post",
        action:"",
      }
    },
    data() {
      return {
        dialogVisible: false,
        listObj: [],
        fileList: [],//上传图片数组
        fileArr:[],//图片数组
      }
    },
    methods: {
      //获取文件
      getFile(file){
        this.file = file
        console.log(file,'file')
      },
      //图片上传
      async uploadImage(){
        let fileFormData = new FormData();
        fileFormData.append('file',this.file.raw); //file是值，就是要传的文件，
        fileFormData.append('type','type'); //type随便传，表示裁剪0.7倍，
        const res =await this.$http('/common/upload',fileFormData,'post',false)
        if(res.code==1){
          const url = res.data.url
          const temporary_url = res.data.temporary_url
          const uid = this.file.uid
          this.fileList.push(url)
          // this.fileList.push({'uid':url})
          this.fileArr.push({'uid':uid,'temporary_url':temporary_url})
          this.listObj.push({'uid':uid,'url':url,'hasSuccess':true})
        }
      },
      handleSubmit() {
        this.$emit('successCBK', this.listObj)
        this.listObj = []
        this.fileList = []
        this.dialogVisible = false
      },
       handleRemove(file) {
        this.fileArr.map((item,index)=>{
          if(item.uid==file.uid){
            this.$http('/common/imageDel',{
              'file':item.temporary_url
            },'post').then(res=>{
              this.fileArr.remove(index)
              this.fileList.remove(index)
            })
          }
        })
      },
    }
  }
</script>

<style lang="scss" scoped>
  .editor-slide-upload {
    margin-bottom: 20px;
    ::v-deep .el-upload--picture-card {
      width: 100%;
    }
  }
</style>
